<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('分配详情') }}</span>
      </div>
      <el-table :data="form.fundFpDetailsList" border class="nowrapTable formTable">
        <el-table-column v-if="queryParams.lpId === undefined" :label="$t('出资人名称')" align="center" min-width="200">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('出资人名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.investorName'" :rules="rules.investorName">
              <el-autocomplete
                v-model="scope.row.investorName"
                popper-class="my-autocomplete"
                clearable
                :fetch-suggestions="querySearch"
                :placeholder="$t('请输入')"
                @select="handleSelect($event, scope.row)"
              >
                <template slot-scope="{ item }">
                  <div>{{ item.userName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParams.lpId !== undefined" :label="$t('基金名称')" align="center" min-width="200">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('基金名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.fundName'">
              <el-input v-model="scope.row.fundName" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('分配批次')" align="center" min-width="150">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('分配批次') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.fpQc'">
              <el-input v-model="scope.row.fpQc" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('分配时间')" align="center" min-width="180">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('分配时间') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.fpTime'">
              <DatePicker
                v-model="scope.row.fpTime"
                :disabled="(!isEmpty(scope.row.fpTime)) && !(isEmpty(scope.row.id))"
                value-format="yyyy-MM-dd"
                :placeholder="$t('分配时间')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('分配总金额') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('分配总金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.totalAmount'" :rules="rules.totalAmount">
              <Money
                v-model="scope.row.totalAmount"
                unit="w"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!--        <el-table-column v-if="isRate" :label="$t('汇率')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('汇率') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.exchangeRate'" :rules="rules.exchangeRate">
              <Money
                v-model="scope.row.exchangeRate"
                unit="rate"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="isRate" :label="$t('分配总金额') +$t('RMB')+ $t('金额单位')" align="center" min-width="140">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('分配总金额RMB') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.totalAmountRmb'">
              <Money
                v-model="scope.row.totalAmountRmb"
                unit="w"
              />
            </el-form-item>
          </template>
        </el-table-column>-->
        <el-table-column :label="$t('本金及费用') + $t('金额单位')" align="center" min-width="120">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('本金及费用') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.principalCost'">
              <Money
                v-model="scope.row.principalCost"
                unit="w"
                @change="calculation"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('Hurdle') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('Hurdle') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.hurdleTheory'">
              <Money
                v-model="scope.row.hurdleTheory"
                unit="w"
                @change="calculation"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('追赶条款') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('追赶条款') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.chaseTerms'">
              <Money
                v-model="scope.row.chaseTerms"
                unit="w"
                @change="calculation"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('剩余分配') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('剩余分配') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.surplusLp'">
              <Money
                v-model="scope.row.surplusLp"
                unit="w"
                @change="calculation"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('税费') + $t('金额单位')" align="center" min-width="130">
          <template slot-scope="scope">
            <el-form-item :prop="'fundFpDetailsList.' + scope.$index + '.taxeFee'">
              <Money
                v-model="scope.row.taxeFee"
                unit="w"
                @change="calculation"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="queryParams.lpId === undefined" :label="$t('操作')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!--            <el-button-->
            <!--              v-hasPermi="['fp:fp:edit']"-->
            <!--              size="small"-->
            <!--              type="text"-->
            <!--              icon="el-icon-edit"-->
            <!--              @click="updateHandle(scope.row)"-->
            <!--            >{{ $t('修改') }}</el-button>-->
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteHandle(scope.row,scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addHandler">{{ $t("添加") }}</el-button>
      </div>
      <!--      <pagination-->
      <!--        v-show="total>0"-->
      <!--        :total="total"-->
      <!--        :page.sync="queryParams.pageNum"-->
      <!--        :limit.sync="queryParams.pageSize"-->
      <!--        @pagination="getList"-->
      <!--      />-->
      <!-- 添加或修改基金分配主表对话框 -->
      <!--      <el-dialog-->
      <!--        :title="title"-->
      <!--        :visible.sync="formOpen"-->
      <!--        :close-on-click-modal="false"-->
      <!--        custom-class="dialogForm"-->
      <!--        append-to-body-->
      <!--      >-->
      <!--        <fundFpDetailsForm ref="fundFpDetailsForm" />-->
      <!--      </el-dialog>-->
    </el-form>
    <div slot="footer" class="dialog-footer" style="position:absolute;right:18px;bottom:18px;">
      <!--保存 取消按钮-->
      <save-btn has-permi="fund:fp" />
    </div>
  </div>
</template>

<script>
import { listFundFpDetails, delFundFpDetails, saveMain } from '@/api/fund/fp/fundFpDetails'
import { getSystemCurrency } from '@/api/system/config'
import { getFundBase } from '@/api/fund/fundBase'
// import fundFpDetailsForm from '@/views/fund/fp/fundFpDetailsForm'
import { listFundInvestorAll } from '@/api/fund/investor/fundInvestor'

export default {
  components: {},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      fpCurr: '',
      tableW: '',
      defCurr: '',
      isRate: false,
      // 基金分配-分配详情表格数据
      fundFpDetailsList: [],
      // 出资人数据集合
      restaurants: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      formOpen: false,
      detailsOpen: false,
      // 查询参数
      queryParams: {
        fundId: this.$route.query.id,
        fpId: undefined,
        lpId: undefined,
        investorId: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        fundFpDetailsList: []
      },
      // 表单校验
      rules: {
          investorName: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
          totalAmount: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
          exchangeRate: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
        }
    }
  },
  created() {
    getSystemCurrency().then(res => {
      this.defCurr = res.data
    })
  },
  methods: {
    /** 查询基金分配-分配详情列表 */
    async getList(data) {
      if (data !== undefined && data.lpId !== undefined) {
        this.queryParams.lpId = data.lpId
        this.queryParams.fundId = data.fundId
        this.isRate = true
      } else {
        // 获取币种
        await getFundBase(this.$route.query.id).then(res => {
          this.fpCurr = res.data.currency
          this.isRate = this.defCurr !== this.fpCurr
        })
      }

      this.loading = true
      listFundFpDetails(this.queryParams).then(response => {
        if (response.rows.length === 0) {
          // 加载出资人信息
          this.loadInvestmentData()
          this.loading = false
        } else {
          this.form.fundFpDetailsList = response.rows
          this.form.id = this.queryParams.fpId
          this.total = response.total
          this.loading = false
        }
      })
    },

    // 表单重置
    reset() {
      this.form = {
        fundFpDetailsList: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      this.formOpen = true
      this.title = this.$t('分配详情')
      this.$nextTick(() => {
        this.$refs.fundFpDetailsForm.init(null)
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.title = this.$t('分配详情')
      this.$nextTick(() => {
        row.isRate = this.isRate
        // 调用form页面的 init 方法初始化数据
        this.$refs.fundFpDetailsForm.init(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row, index) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            delFundFpDetails(row.id)
          }).then(() => {
          this.form.fundFpDetailsList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {
          })
      } else {
        this.form.fundFpDetailsList.splice(index, 1)
      }
    },
    addHandler() {
      const row = {
        id: undefined,
        fundId: this.$route.query.id,
        fpId: undefined,
        investorId: undefined,
        investorName: undefined,
        assignItems: undefined,
        fpTime: undefined,
        principalCost: undefined,
        priorityReturn: undefined,
        chaseTerms: undefined,
        surplusLp: undefined,
        taxeFee: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        totalAmount: undefined,
        exchangeRate: undefined,
        totalAmountRmb: undefined
      }
      if (!(this.form.fundFpDetailsList instanceof Array)) {
        this.$set(this.form, 'fundFpDetailsList', [])
      }
      this.$nextTick(() => {
        this.form.fundFpDetailsList.push(row)
      })
    },
    // 加载出资人信息
    loadInvestmentData() {
      listFundInvestorAll({ fundId: this.$route.query.id }).then(response => {
        this.restaurants = response.data
        this.form.fundFpDetailsList = []
        // 默认带出分配明细的出资人
        if (this.restaurants !== undefined && this.restaurants !== null) {
          this.restaurants.forEach((item, index) => {
            this.addHandler()
            this.$nextTick(() => {
              this.handleSelect(item, this.form.fundFpDetailsList[index])
            })
          })
        }
      })
    },
    // 选择投资主体触发方法
    querySearch(queryString, cb) {
      listFundInvestorAll({ fundId: this.$route.query.id }).then(response => {
       this.restaurants = response.data
        const restaurants = this.restaurants
        const results = queryString ? (this.restaurants.filter(item => item.userName.includes(queryString))) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      })
    },
    /**
     * 选择投资主体数据
     * @param item   选中的主体
     * @param row    当前行数据
     * @param index  当前行索引
     */
    handleSelect(item, row) {
      // 遍历判断是否存在这个投资主体
      const temp = this.form.fundFpDetailsList.find(detail => detail.investorId === item.id)
      if (temp) {
        this.msgError(this.$t('不能重复选择出资人，请重新选择或者输入！'))
      } else {
        // 出资人ID
        row.investorId = item.id
        // 出资人名称
        row.investorName = item.userName
        this.form.id = this.queryParams.fpId
      }
    },
    // 计算总金额
    calculation() {
      this.form.fundFpDetailsList.forEach(item => {
        item.totalAmount =
          this.transZero(item.principalCost) +
          this.transZero(item.priorityReturn) +
          this.transZero(item.surplusLp) +
          this.transZero(item.chaseTerms) -
          this.transZero(item.taxeFee)
        if (!this.isRate) {
          item.exchangeRate = 1
        }
         item.totalAmountRmb = this.transZero(item.totalAmount) * this.transZero(item.exchangeRate)
      })
    },
    transZero(val) {
      if (val !== undefined && val !== null && val !== '') {
        return val
      }
      return 0
    },
    // 取消按钮
    cancel() {
      if (this.$parent.$parent.formOpen2 !== undefined) {
        this.$parent.$parent.formOpen2 = false
      }
      this.$parent.$parent.detailsOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.detailsOpen !== undefined) {
        this.$parent.$parent.detailsOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.form.fundFpDetailsList.forEach(item => {
        if ((item.exchangeRate === null || item.exchangeRate === undefined || item.exchangeRate === '') && !this.isRate) {
          item.exchangeRate = 1
        }
        if ((item.totalAmountRmb === null || item.totalAmountRmb === undefined || item.totalAmountRmb === '') && !this.isRate) {
          item.totalAmountRmb = item.totalAmount
        }
      })
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveMain(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    }
  }
}
</script>
